#!/usr/bin/env bash

set -e

mkdir -p src/main/clojure/cljs/vendor
cd src/main/clojure/cljs

DJSON_RELEASE="2.4.0"
TRANSIT_RELEASE="1.0.329"
TREADER_RELEASE="1.4.2"

rm -rf data.json
git clone -b "v$DJSON_RELEASE" --depth 1 git@github.com:clojure/data.json.git
mkdir -p vendor/clojure/data
mv data.json/src/main/clojure/clojure/data/json.clj vendor/clojure/data/
rm -rf data.json
DATA_JSON_FILE=`mktemp /tmp/json.clj.XXXXXXXXXXX`
sed -e 's/clojure.data.json/cljs.vendor.clojure.data.json/' vendor/clojure/data/json.clj > $DATA_JSON_FILE
mv $DATA_JSON_FILE vendor/clojure/data/json.clj

rm -rf transit-clj
git clone -b "v$TRANSIT_RELEASE" --depth 1 git@github.com:cognitect/transit-clj.git
mkdir -p vendor/cognitect
mv transit-clj/src/cognitect/transit.clj vendor/cognitect/
rm -rf transit-clj
TRANSIT_FILE=`mktemp /tmp/transit.clj.XXXXXXXXXXX`
sed -e 's/ns cognitect.transit/ns cljs.vendor.cognitect.transit/' vendor/cognitect/transit.clj > $TRANSIT_FILE
mv $TRANSIT_FILE vendor/cognitect/transit.clj
TRANSIT_FILE=`mktemp /tmp/transit.clj.XXXXXXXXXXX`
sed -e 's/cognitect.transit.WithMeta/cljs.vendor.cognitect.transit.WithMeta/' vendor/cognitect/transit.clj > $TRANSIT_FILE
mv $TRANSIT_FILE vendor/cognitect/transit.clj

rm -rf tools.reader
rm -rf vendor/clojure/tools
git clone -b "v$TREADER_RELEASE" --depth 1 git@github.com:clojure/tools.reader.git
mkdir -p vendor/clojure/tools
mv tools.reader/src/main/clojure/clojure/tools/* vendor/clojure/tools/
rm -rf tools.reader

echo "rewriting tool.reader namespaces"
find vendor/clojure/tools -name '*.clj' -print0 | xargs -0 sed -iBAK 's/clojure.tools/cljs.vendor.clojure.tools/g'
find vendor/clojure/tools -name '*BAK' -delete
